const multer = require('multer');
const fs = require('fs');

function createDir(s, n = 0) {
  // 'public/upload/2022/8/31/'
  const end = s.indexOf('/', n) + 1
  try {
    fs.statSync(
      s.slice(
        0,
        end
      )
    );
  } catch (err) {
    fs.mkdirSync(
      s.slice(
        0,
        end
      )
    );
  }

  if (end < s.length) {
    createDir(s, end);
  }
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {

    const date = new Date();
    let s = 'public/upload/';

    s += date.getFullYear() + '/';

    s += date.getMonth() + 1 + '/';

    s += date.getDate() + '/';

    //创建目录
    createDir(s);
    cb(null, s)
  },
  filename: function (req, file, cb) {
    let s = file.originalname;
    s = s.slice(s.lastIndexOf('.'))
    s = new Date().getTime() + s;
    s = Math.floor(Math.random() * 1000000000) + '-' + s;
    cb(null, s)
  }
})

const upload = multer({ storage: storage });
module.exports.upload = upload;